const jwt = require('jsonwebtoken')

function sign(payload, time) {
    return jwt.sign(payload, 'secretKey', { expiresIn: time || '1d' })
}

function verify() {
    return async (ctx, next) => {
        const token = ctx.headers.authorization
        if (!token) {
            ctx.status = 401
            ctx.body = { code: '0', msg: '请重新登录' }
            return
        }
        try {
            const decoded = jwt.verify(token, 'secretKey')
            ctx.userId = decoded.id
            await next()
        } catch (err) {
            ctx.status = 401
            ctx.body = { code: '0', msg: '登录失效' }
        }
    }
}

function refreshVerify(token) {
    try {
        const decoded = jwt.verify(token, 'secretKey')
        return decoded
    } catch (error) {
        return false
    }
}

module.exports = { sign, verify, refreshVerify }
